﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Viettel.VOFFICE.DAO.DAL.Paging;
using Viettel.VOFFICE.DAO.Models;

namespace Viettel.VOFFICE.DAO.DAL.Repository
{
    /// <summary>
    /// quyền, và nhóm qyền có trong hê thống
    /// </summary>
    public class RoleRepository : IRepository<aspnet_Roles>
    {
        private VOFFICEContext context;
        public RoleRepository(VOFFICEContext context)
        {
            if (context == null)
            {
                throw new Exception("Context must be init");
            }
            this.context = context;
        }

        #region IRepository
        public IEnumerable<aspnet_Roles> Get()
        {
            try
            {
                return context.aspnet_Roles.ToList();
            }
            catch (Exception)
            {
                return null;
            }
        }

        public aspnet_Roles GetById(object id)
        {
            try
            {
                return context.aspnet_Roles.Find(id);
            }
            catch (Exception)
            {
                return null;
            }
        }

        public void Insert(aspnet_Roles T)
        {
            try
            {
                var existsRoles = FindByName(T.RoleName.ToLower());
                if (existsRoles != null && existsRoles.Any())
                {
                    throw new DuplicateWaitObjectException();
                }
                context.aspnet_Roles.Add(T);
                Save();
            }
            catch (Exception)
            {
                throw new NotSupportedException();
            }
        }

        public void Delete(object id)
        {
            var roleEntity = GetById((Guid)id);
            context.aspnet_Roles.Attach(roleEntity);
            context.aspnet_Roles.Remove(roleEntity);
            Save();
        }

        public void Update(aspnet_Roles T)
        {
            context.Entry(T).State = EntityState.Modified;
            Save();
        }

        public void Save()
        {
            context.SaveChanges();
        }


        public IEnumerable<aspnet_Roles> FindByName(object s)
        {
            var query = (from i in context.aspnet_Roles
                         where i.LoweredRoleName.Equals((string)s)
                         select i);
            return query.ToList();
        }
        public void Delete(aspnet_Roles T)
        {
            context.aspnet_Roles.Attach(T);
            context.aspnet_Roles.Remove(T);
            Save();
        }
        #endregion

        #region Extend Function
        /// <summary>
        /// Danh sach phan trang
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public PagedList<aspnet_Roles> GetWithPaging(int pageIndex, int pageSize)
        {
            return context.aspnet_Roles.OrderBy(o => o.RoleName).Paginate(pageIndex, pageSize);
        }

        public aspnet_Roles GetByName(object sO)
        {
            try
            {
                var lowerdName = sO.ToString();
                return context.aspnet_Roles.FirstOrDefault(s => s.LoweredRoleName.Equals(lowerdName));
            }
            catch (Exception)
            {
                return null;
            }
        }

        public string GetRoleDisplayName(string[] roleName)
        {
            try
            {
                return string.Join(", ", context.aspnet_Roles.Where(o => roleName.Contains(o.RoleName)).Select(s => s.RoleDisplayName).ToArray());
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }

        public string GetUserByControllerActionName(string controllerName, string actionName)
        {
            try
            {

                var queryRoles = (from i in context.aspnet_Roles
                                  join j in context.v_RoleControllerActionMapping on i.RoleId equals j.RoleId
                                  where j.ControllerName.Equals(controllerName)
                                  & j.ActionName.Equals(actionName)
                                  select i.RoleId).ToArray();
                var queryUserInRole = (from i in context.vw_aspnet_UsersInRoles
                                       where queryRoles.Contains(i.RoleId)
                                       select i.UserId).ToArray();
                var queryUsers = (from i in context.v_UserControllerActionMapping
                                  where i.ActionName.Equals(actionName)
                                  & i.ControllerName.Equals(controllerName)
                                  select i.UserId).ToArray();
                var combindUser = queryUserInRole.Concat(queryUsers).ToArray();
                var combindUserName = (from i in context.aspnet_Users
                                       where combindUser.Contains(i.UserId)
                                       select i.UserName).ToArray();
                return string.Join(",", combindUserName);
            }
            catch
            {
                return string.Empty;
            }
        }
        public Guid[] GetAllApplicationId()
        {
            try
            {
                var arrAppId = (from i in context.aspnet_Applications
                                select i.ApplicationId).ToArray();
                return arrAppId;
            }
            catch (Exception)
            {

                throw;
            }
        }
        public Guid GetMailApplicationId(string applicationName)
        {
            var applicationId = (from i in context.aspnet_Applications
                                 where i.LoweredApplicationName.Equals(applicationName.ToLower())
                                 select i.ApplicationId).FirstOrDefault();
            return applicationId;
        }
        #endregion

        /// <summary>
        /// Lấy ra tất cả các role theo loại truyền vào
        /// </summary>
        /// <returns></returns>
        public IEnumerable<aspnet_Roles> GetByType()
        {
            return context.aspnet_Roles.Select(o => o);
        }
    }
}
